package com.py.credit.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.entity.Account;
import com.py.credit.entity.Database;
import com.py.credit.entity.DictDetailEntity;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.ResourceModelFieldsEnum;
import com.py.credit.service.ModelBaseService;
import com.py.credit.service.SysDictService;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.MapCache;
import com.py.framework.core.common.Page;
import com.py.framework.core.rest.support.RestServiceResult;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags = "model", description = "机构模型前台")
@RestController
@RequestMapping(value = "/model")
public class FrontModelController {

	private static final String FRONT_F_TABLE_ID = "fmodellist";

	@Autowired
	private ModelBaseService modelBaseService;

	@Autowired
	private SysDictService sysDictService;

	@ApiOperation(value = "分页获取模型", httpMethod = "GET", produces = "application/json")
	@RequestMapping(value = "/front/getModelList.json", method = RequestMethod.GET)
	public RestServiceResult<List<Map<String, Object>>> getModelListForPge(
			@RequestParam(value = "condition", defaultValue = "") String condition,
			@RequestParam(value = "kId", defaultValue = "") String kId,
			@RequestParam(value = "areaId", defaultValue = "") String areaId,
			@RequestParam(value = "industryId", defaultValue = "") String industryId, Page page,
			HttpServletRequest request) {

		Account account = (Account) request.getSession().getAttribute("ACCOUNT");

		List<Map<String, Object>> modelListForPage = new ArrayList<>();

		if (account != null) {
			String[] additionalColumns = { "id", "orgId", "mainType" };
			String[] configColumns = (String[]) MapCache.get(account.getId() + "_" + FRONT_F_TABLE_ID);

			List<String> showColumns = (configColumns == null || configColumns.length == 0)
					? ResourceModelFieldsEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);

			modelListForPage = modelBaseService.getModelListByConditionForPage(account.getOrgId(), showColumns,
					additionalColumns, page, condition, kId, areaId, industryId);

		} else {
			ExceptionLogger.error("FrontModelController#getFOrgList", "未获取到当前用户信息！");
		}

		return new RestServiceResult<List<Map<String, Object>>>(page.getTotalCount(), modelListForPage);

	}

	@ApiOperation(value = "获取高级搜索条件", httpMethod = "GET", produces = "application/json")
	@RequestMapping(value = "/front/getAdvancedConditionColumns.json", method = RequestMethod.GET)
	public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns() {

		return new RestServiceResult<List<OptionalColumn>>(ResourceModelFieldsEnum.getAdvancedConditionColumns());

	}

	@ApiOperation(value = "获取表头列", httpMethod = "GET", produces = "application/json")
	@RequestMapping(value = "/front/getOptionalColums.json", method = RequestMethod.GET)
	public RestServiceResult<List<OptionalColumn>> getOptionalColums() {

		return new RestServiceResult<List<OptionalColumn>>(ResourceModelFieldsEnum.getOptionalColumns());

	}

	@ApiOperation(value = "自定义展示列", httpMethod = "POST", produces = "application/json")
	@RequestMapping(value = "/front/addColumns.json", method = RequestMethod.POST)
	public RestServiceResult<Object> addColumns(
			@ApiParam(required = true, name = "columns", value = "展示列数组") @RequestParam(value = "columns", required = true) String[] columns,
			HttpServletRequest request) {

		HttpSession session = request.getSession();

		Account account = (Account) session.getAttribute("ACCOUNT");

		if (account != null) {

			MapCache.set(account.getId() + "_" + FRONT_F_TABLE_ID, columns);

		} else {

			ExceptionLogger.error("FrontModelController#addFColumns", "未获取到当前用户信息！");

		}

		return new RestServiceResult<Object>();

	}

	@ApiOperation(value = "导出列表", httpMethod = "GET")
	@RequestMapping("/front/export.json")
	public void fExport(
			@ApiParam(required = true, name = "condition", value = "搜索条件") @RequestParam(value = "condition", defaultValue = "", required = true) String condition,
			@ApiParam(required = true, name = "columnEN", value = "导出列") @RequestParam(value = "columnEN", required = true) String columnEN,
			@RequestParam(value = "kId", defaultValue = "") String kId,
			@RequestParam(value = "areaId", defaultValue = "") String areaId,
			@RequestParam(value = "industryId", defaultValue = "") String industryId, HttpServletResponse response,
			HttpServletRequest request, Page page) throws IOException {

		page.setLimit(1000);

		HttpSession session = request.getSession();

		Account account = (Account) session.getAttribute("ACCOUNT");

		if (account != null) {

			List<String> columns = JSONArray.parseArray(columnEN, String.class);

			List<Map<String, Object>> data = modelBaseService.getModelListByConditionForPage(account.getOrgId(),
					columns, null, page, condition, kId, areaId, industryId);

			List<OptionalColumn> optionalColumns = ResourceModelFieldsEnum.getOptionalColumns();

			ExcelUtil.downloadExcel(response, data, "模型列表", "模型列表", columns, optionalColumns);
		} else {
			ExceptionLogger.error("FrontModelController#fExport", "未获取到当前用户信息！");
		}

	}

	@RequestMapping(value = "/front/selectCheckProcessForOrg.json", method = RequestMethod.GET)
	@ApiOperation(value = "获取审核流程", httpMethod = "GET")
	public RestServiceResult<Map> selectCheckProcessForOrg(
			@ApiParam(required = true, name = "id", value = "模型id") @RequestParam(required = true) String id,
			@ApiParam(required = true, name = "orgId", value = "机构id") @RequestParam(required = true) String orgId,
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		HttpSession session = request.getSession();

		Account account = (Account) session.getAttribute("ACCOUNT");

		Map m = null;
		if (account != null) {

			m = modelBaseService.selectCheckProcessForOrg(orgId, id);

		} else {

			ExceptionLogger.error("FrontModelController#addFColumns", "未获取到当前用户信息！");

		}
		return new RestServiceResult<Map>(m);
	}

	@RequestMapping(value = "/front/saveCheckProcessForOrg.json", method = RequestMethod.POST)
	@ApiOperation(value = "保存审核流程", httpMethod = "POST")
	public RestServiceResult<Object> saveCheckProcessForOrg(
			@ApiParam(required = true, name = "id", value = "模型id") @RequestParam(required = true) String id,
			@ApiParam(required = true, name = "orgId", value = "机构id") @RequestParam(required = true) String orgId,
			@ApiParam(required = true, name = "checkType", value = "审核类型") @RequestParam(required = true) String checkType,
			@ApiParam(required = true, name = "checkProcess", value = "审核流程") @RequestParam(required = true) String checkProcess,
			@ApiParam(required = true, name = "templateType", value = "模板类型") @RequestParam(required = true) String templateType,
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		HttpSession session = request.getSession();

		Account account = (Account) session.getAttribute("ACCOUNT");
		RestServiceResult<Object> o = new RestServiceResult<Object>();
		if (account != null) {

			modelBaseService.saveCheckProcessForOrg(orgId, id, checkType, checkProcess, templateType);

		} else {

			ExceptionLogger.error("FrontModelController#addFColumns", "未获取到当前用户信息！");
			o.setCode(-1);
		}
		return new RestServiceResult<Object>(o);
	}

	@RequestMapping(value = "/front/getDictDetails.json", method = RequestMethod.GET)
	public RestServiceResult<List<DictDetailEntity>> getDictDetails(
			@RequestParam(value = "dictKey", defaultValue = "", required = true) String dictKey,
			HttpServletRequest request) {
		RestServiceResult<List<DictDetailEntity>> result = new RestServiceResult<>();
		try {
			List<DictDetailEntity> list = sysDictService.getDictDetails(dictKey, StringUtils.EMPTY);
			result.setData(list);
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("获取字典详情值失败！");
			return result;
		}
		return result;
	}

	@RequestMapping(value = "/front/getDbList.json")
	public RestServiceResult<List<Database>> getDbList() {

		return new RestServiceResult<List<Database>>(modelBaseService.getDbList(null));

	}

}
